<template>
  <el-dialog
    title="图片库"
    v-model="showSelectPictureDialogFlag"
    left
    destroy-on-close="true"
    :append-to-body="true"
    class="drag-dialog small-padding-dialog"
    width="80%"
    @open="getList"
    @close="close"
    align-center
  >
    <el-tabs v-model="activeName" type="border-card" @tab-click="selected">
      <el-tab-pane label="图片库" name="library">
        <ContentWrap>
          <div class="demo-image__error">
            <el-checkbox-group v-model="checked" @change="selectedPicture">
              <div class="block" v-for="(item, index) in list" :key="item">
                <span class="checkbox">
                  <el-checkbox id="pictureId" :indeterminate="false" :label="item" name="id">
                    <br />
                  </el-checkbox>
                </span>
                <el-image
                  fit="contain"
                  :src="item.url"
                  :preview-src-list="previewList"
                  :initial-index="initPreview"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  @show="previewShow(index)"
                />
                <el-text class="demonstration">{{ item.name }}</el-text>
                <el-text class="demonstration" type="info" size="small">{{
                  item.createTime
                }}</el-text>
              </div>
            </el-checkbox-group>
          </div>
          <!-- 分页 -->
          <Pagination
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNo"
            :total="total"
            @pagination="getList"
          />
        </ContentWrap>
      </el-tab-pane>
      <!--      <el-tab-pane label="个人素材" name="material">-->
      <!--        <ContentWrap>-->
      <!--          <div class="demo-image__error">-->
      <!--            <el-checkbox-group v-model="checked" @change="selectedPicture">-->
      <!--              <div class="block" v-for="(item, index) in list" :key="item">-->
      <!--                <span class="checkbox">-->
      <!--                  <el-checkbox id="pictureId" :indeterminate="false" :label="item.id" name="id">-->
      <!--                    <br />-->
      <!--                  </el-checkbox>-->
      <!--                </span>-->
      <!--                <el-image-->
      <!--                  fit="contain"-->
      <!--                  :src="item.url"-->
      <!--                  :preview-src-list="previewList"-->
      <!--                  :initial-index="initPreview"-->
      <!--                  :zoom-rate="1.2"-->
      <!--                  :max-scale="7"-->
      <!--                  :min-scale="0.2"-->
      <!--                  @show="previewShow(index)"-->
      <!--                />-->
      <!--                <el-text class="demonstration">{{ item.name }}</el-text>-->
      <!--                <el-text class="demonstration" type="info" size="small">{{-->
      <!--                  item.createTime-->
      <!--                }}</el-text>-->
      <!--              </div>-->
      <!--            </el-checkbox-group>-->
      <!--          </div>-->
      <!--          &lt;!&ndash; 分页 &ndash;&gt;-->
      <!--          <Pagination-->
      <!--            v-model:limit="queryParams.pageSize"-->
      <!--            v-model:page="queryParams.pageNo"-->
      <!--            :total="total"-->
      <!--            @pagination="getList"-->
      <!--          />-->
      <!--        </ContentWrap>-->
      <!--      </el-tab-pane>-->
      <el-tab-pane label="本地上传" name="local">
        <ContentWrap>
          <el-upload
            ref="upload"
            class="upload-demo"
            :http-request="saveImageUpload"
            list-type="picture"
            multiple="true"
            :show-file-list="false"
            :accept="PictureFormat"
            :before-upload="beforeAvatarUpload"
          >
            <el-button type="primary">点击上传</el-button>
            <div class="el-upload__tip">
              支持格式：{{ PictureFormat }}，图片大小不超过{{ PictureSize }}M
            </div>
          </el-upload>
          <div style="margin-top: 10px">
            <el-card v-for="(item, index) in imageList" :key="index" class="box-card">
              <div class="text-item">
                <Icon icon="mdi:remove" @click="removeImage(index)" />
                <div class="demo-image__error">
                  <div class="block-left">
                    <el-form label-width="80px" label-position="right">
                      <el-form-item label="名称" required>
                        <el-input v-model="item.name" />
                      </el-form-item>
                      <el-form-item label="关键字">
                        <el-input v-model="item.keywords" />
                      </el-form-item>
                      <el-form-item label="图片分类">
                        <el-select v-model="pictureForm.classify" placeholder="请选择图片分类">
                          <el-option
                            v-for="item in classifyList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="标签">
                        <el-input v-model="item.labels" />
                      </el-form-item>
                    </el-form>
                  </div>
                  <div class="block-right">
                    <el-image style="width: 100%; height: 100%" fit="contain" :src="item.url" />
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </ContentWrap>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="define">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessageBox, FormInstance, UploadProps } from 'element-plus'
import * as pictureApi from '@/api/picture'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { PictureFormat, PictureSize } from '@/utils/config'
import * as metaApi from '@/api/meta'

const queryFormRef = ref<any>()
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const previewList = ref([])
const initPreview = ref(0)
const showImageUploadDialogFlag = ref(false)
const pictureForm = ref({})
const saved = ref(false)
const updated = ref(false)
const dialogTitle = ref('图片上传')

const pictureFormRef = ref<FormInstance>()

const classifyList = ref([])

const checked = ref([])
const activeName = ref('local')
const innerVisible = ref(true)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  type: 10,
  name: null,
  size: null,
  createTime: []
})

const showSelectPictureDialogFlag = ref(false)

const openSelectPicture = () => {
  showSelectPictureDialogFlag.value = true
  getClassify()
}
const close = () => {
  showSelectPictureDialogFlag.value = false
}

const updatePicture = (id) => {
  getClassify()
  showImageUploadDialogFlag.value = true
  saved.value = true
  updated.value = true
  dialogTitle.value = '图片修改'
  pictureApi.selectOne(id).then((res) => {
    pictureForm.value = res
    if (pictureForm.value.classify) {
      pictureForm.value.classify = Number(pictureForm.value.classify)
    }
  })
}

const removeImage = (index) => {
  imageList.value.splice(index, 1)
}

const secretList = ref([
  {
    value: '1',
    label: '绝密'
  },
  {
    value: '2',
    label: '机密'
  },
  {
    value: '3',
    label: '秘密'
  }
])

const colorList = ref([
  {
    value: '1',
    label: '分类一'
  },
  {
    value: '2',
    label: '分类一'
  },
  {
    value: '3',
    label: '分类一'
  }
])

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
const previewShow = (index) => {
  initPreview.value = index
}
const openImageUpload = () => {
  showImageUploadDialogFlag.value = true
  updated.value = false
  getClassify()
}

//上传前验证文件大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  let size = Number(PictureSize)
  if (rawFile.size / 1024 / 1024 > Number(PictureSize)) {
    ElMessage.error('Avatar picture size can not exceed ' + size + 'MB!')
    return false
  }
  return true
}

const selectedPicture = (value) => {
  console.log(value)
}

const getList = async () => {
  loading.value = true
  try {
    const data = await pictureApi.page(queryParams)
    list.value = data.list
    total.value = data.total
    previewList.value = []
    list.value.forEach((key, index) => {
      previewList.value.push(key.url)
    })
  } finally {
    loading.value = false
  }
}
const getClassify = async () => {
  const data = await pictureApi.getPictureClassify()
  classifyList.value = data
}

const imageList = ref([])

const saveImageUpload = async (content) => {
  let form = new FormData()
  console.log(content.file)
  form.append('file', content.file)
  const data = await pictureApi.uploadMaterial(form)
  data.data.name = content.file.name
  imageList.value.push(data.data)
}

const closeDialog = () => {
  if (saved.value && !updated.value) {
    ElMessageBox.confirm('现在退出将不对图片进行保存，是否继续？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      showImageUploadDialogFlag.value = false
      pictureForm.value = {}
      saved.value = false
    })
  } else {
    showImageUploadDialogFlag.value = false
    saved.value = false
  }
}

const handleQuery = () => {
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/**
 * 表单提交
 */
const saveForm = () => {
  pictureFormRef.value.validate(async (valid) => {
    console.log(valid)
    if (valid) {
      console.log(pictureForm.value)
      pictureApi.savePicture(pictureForm.value).then((res) => {
        console.log(res)
        showImageUploadDialogFlag.value = false
        saved.value = false
        pictureForm.value = {}
        getList()
      })
    }
  })
}

const define = async () => {
  if (activeName.value == 'local') {
    await metaApi.addPicture(props.dataId, props.fieldId, imageList.value)
  } else if (activeName.value == 'material') {
    alert('素材库')
  } else if (activeName.value == 'library') {
    await metaApi.addPicture(props.dataId, props.fieldId, checked.value)
  }
  close()
  refresh()
}

const props = defineProps({
  dataId: String,
  fieldId: String
})

const refresh: any = inject('getList')
defineExpose({
  openSelectPicture
})
</script>
<style lang="scss" scoped>
.block-left {
  display: inline-block;
  width: 70%;
  padding: 30px 20px;
  text-align: center;
  vertical-align: top;
  border-right: solid 1px var(--el-border-color);
  box-sizing: border-box;
}

.block-right {
  display: inline-block;
  width: 30%;
  padding: 30px 20px;
  text-align: center;
  vertical-align: top;
  border-right: solid 1px var(--el-border-color);
  box-sizing: border-box;
}

.dialog-footer {
  text-align: center;
}

.body {
  margin: 0;
}

.demo-image__error .block {
  display: inline-block;
  width: 20%;
  height: 330px;
  padding: 30px 20px;
  text-align: center;
  vertical-align: top;
  border-right: solid 1px var(--el-border-color);
  box-sizing: border-box;
}

.demo-image__error .block .more {
  float: right;
  color: #8c8a8a;
}

.demo-image__error .demonstration {
  display: block;
  margin-top: 10px;
  margin-bottom: 20px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  text-align: left;
}

.demo-image__error .datetime {
  display: block;
  margin-top: 10px;
  font-size: 14px;
  color: #666;
  text-align: left;
}

.demo-image__error .checkbox {
  display: block;
  margin-bottom: 10px;
  font-size: 14px;
  text-align: left;
}

.demo-image__error .el-image {
  width: 100%;
  height: 100%;
  max-width: 300px;
  max-height: 200px;
}

.demo-image__error .image-slot {
  display: flex;
  width: 100%;
  height: 100%;
  font-size: 30px;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color-light);
  justify-content: center;
  align-items: center;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.option {
  display: flex;
  float: right;
  color: #8c8e91;
  cursor: pointer;
  align-items: center;
}
.icon-card {
  position: absolute;
  top: 0.2rem;
  right: 0.2rem;
  line-height: 0.2rem;
  cursor: pointer;
  width: 10px;
  height: 10px;
}
</style>
